package com.liu.voluntary.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.voluntary.mapper.ActivityMapper;
import com.liu.voluntary.mapper.OrderMapper;
import com.liu.voluntary.mapper.SignMapper;
import com.liu.voluntary.mapper.UserMapper;
import com.liu.voluntary.pojo.Activity;
import com.liu.voluntary.pojo.Order;
import com.liu.voluntary.pojo.Sign;
import com.liu.voluntary.pojo.User;
import com.liu.voluntary.handler.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
//import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Controller
@Slf4j
public class SignController {

    @Resource
    private ActivityMapper activityMapper;

    @RequestMapping("/toAddSignPage/{id}")
    public String toAddSignPage(@PathVariable(value = "id") String id, Model model) {

        Activity activity = activityMapper.selectById(id);
        model.addAttribute("activity", activity);

        return "addSign";
    }


    @Resource
    private SignMapper signMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private UserMapper userMapper;
//    @Resource
//    private SimpMessagingTemplate messagingTemplate;
    @Resource
    private WebSocket webSocket;
    @RequestMapping("/toAddSign")
    public String toSign(@RequestParam("longitude") Double  longitude,
                         @RequestParam("latitude") Double  latitude,
                         @RequestParam("startTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
                         @RequestParam("sustainTime") Integer sustainTime,
                         @RequestParam("activityName") String activityName,
                         @RequestParam("address") String address,
                         @RequestParam("message") String message,
                         HttpSession session, HttpServletRequest request) {
        
        log.info("开始处理签到发布请求");
        log.info("活动名称: {}, 地址: {}, 持续时间: {}分钟", activityName, address, sustainTime);
        
        Sign sign = new Sign();
        sign.setLongitude(longitude);
        sign.setLatitude(latitude);
        sign.setStartTime(startTime);
        sign.setSustainTime(sustainTime);
        sign.setActivityName(activityName);
        sign.setActivityAddress(address);

        try {
            signMapper.insert(sign);
            log.info("签到记录已插入数据库，ID: {}", sign.getId());
        } catch (Exception e) {
            log.error("插入签到记录失败", e);
            return "signList";
        }

        // 构建签到消息
        String signMessage = String.format(
            "【签到提醒】\n活动：%s\n地点：%s\n持续时间：%d分钟\n%s\n请及时前往签到！",
            activityName, address, sustainTime, message
        );

        // 查找报名了该活动的用户
        QueryWrapper<Order> orderQuery = new QueryWrapper<>();
        orderQuery.eq("activity_name", activityName);
        List<Order> orders = orderMapper.selectList(orderQuery);

        // 记录发送结果
        int successCount = 0;
        int failCount = 0;

        // 向每个报名用户发送签到消息
        for (Order order : orders) {
            User user = userMapper.selectById(order.getUserId());
            if (user != null && user.getMobile() != null) {
                try {
                    boolean sent = webSocket.sendMessageToUser(user.getMobile(), signMessage);
                    if (sent) {
                        successCount++;
                        log.info("成功发送签到消息给用户: {}", user.getMobile());
                    } else {
                        failCount++;
                        log.warn("用户{}不在线，无法发送签到消息", user.getMobile());
                    }
                } catch (Exception e) {
                    failCount++;
                    log.error("发送签到消息给用户{}失败: {}", user.getMobile(), e.getMessage());
                }
            }
        }

        if (failCount > 0) {
            log.warn("签到消息发送完成 - 成功: {}, 失败: {} - 部分用户可能未收到消息", successCount, failCount);
        } else {
            log.info("签到消息发送完成 - 成功: {}, 失败: {}", successCount, failCount);
        }
        return "redirect:/toSignList";
    }




    @RequestMapping("/signDetail/{id}")
    public String signDetail(@PathVariable(value = "id") String id, Model model) {


        return "signDetail";
    }






    @RequestMapping("/toSignList")
    public String toSignList(Model model) {


        List<Sign> signs = signMapper.selectList(null);

        model.addAttribute("signs", signs);


        return "signList";
    }



    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("/toSign")
    public String toSign(@CookieValue("Ticket") String Ticket,Model model,@RequestParam("id") Long activityId) {


        Activity activity = activityMapper.selectById(activityId);

        // 确保 activity 包含经纬度信息
        if (activity != null && activity.getLat() != null && activity.getLng() != null) {
            model.addAttribute("activity", activity);
        } else {
            // 如果没有经纬度信息，处理错误情况
            return "errorPage"; // 或者其他处理方式
        }
        User user = (User) redisTemplate.opsForValue().get("user:" + Ticket);

        model.addAttribute("activity",activity);
        model.addAttribute("user",user);

        return "sign";
    }






}
